<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use Exception;

/**
 * 订单管理
 *
 * @icon   fa fa-circle-o
 * @remark 主要用于管理订单
 */
class Order extends Backend
{

    /**
     * @var \app\admin\model\Order
     */
    protected $model = null;

    protected $searchFields = 'company,content';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Order');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
				->with(['admin'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
	
	/**
     * 添加
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
		
		$this->token();
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $result = false;
        Db::startTrans();
        try {
			$params['admin_id'] = $this->auth->id;
			$result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
		
		if($result == false)
		{
			$this->error('添加失败');
		}

        $this->success('添加成功');
    }

    /**
     * 删除
     * @param array $ids
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $count = $this->model->where('id', 'in', $ids)->delete();
			if ($count) {
				$this->success();
			}
        }
        $this->error(__('No rows were deleted'));
    }
}
